#include <iostream>
#include <stack>

using namespace std;

class Solution {
private:
    stack<int> len_stack;
    void reverse_array(char* begin, char* end) {
        while (begin < end) {
            swap(*begin, *end);
            begin++;
            end--;
        }
    }
    void clear_blank(string& s) {
        if (s[0] == ' ') {
            int index2 = 1;
            while (s[index2] == ' ') {
                index2++;
            }
            clear_blank(s, 0, 0, index2);
            return;
        }
        int begin = 0;
        for (int i = 1; i < s.length() - 1; i++) {
            if (s[i] == ' ') {
                if (s[i + 1] == ' ') {
                    clear_blank(s, begin, i, i + 1);
                    return;
                } else {
                    len_stack.push(i - begin);
                    begin = i + 1;
                }
            }
        }
        if (s[s.length() - 1] != ' ') {
            len_stack.push(s.length() - begin);
        } else {
            len_stack.push(s.length() - 1 - begin);
            s.resize(s.length() - 1);
        }
    }
    void clear_blank(string& s, int begin, int index1, int index2) {
        for (; index2 < s.length() - 1; ) {
            if (s[index2] == ' ') {
                if (s[index2 + 1] == ' ') {
                    index2++;
                } else {
                    s[index1] = s[index2];
                    len_stack.push(index1 - begin);
                    begin = index1 + 1;
                    index1++;
                    index2++;
                }
            } else {
                s[index1] = s[index2];
                index1++;
                index2++;
            }
        }
        if (s[index2] != ' ') {
            s[index1] = s[index2];
            s.resize(index1 + 1);
            len_stack.push(index1 + 1 - begin);
        } else {
            s.resize(index1);
            len_stack.push(index1 - begin);
        }

    }
    void reverse_sub(string& s) {
        int begin = 0;
        int end = 0;
        while (len_stack.size() > 0) {
            end = begin + len_stack.top();
            len_stack.pop();
            reverse_array(s.data() + begin, s.data() + end - 1);
            begin = end + 1;
        }
    }
public:
    string reverseWords(string s) {
        if (s.length() == 0) {
            return s;
        }
        clear_blank(s);
        reverse_array(s.data(), s.data() + s.length() - 1);
        reverse_sub(s);
        return s;
    }
};

int main() {
    string input = " 1";
    Solution solution;
    string output = solution.reverseWords(input);
    cout << output << endl;
    return 0;
}

